package com.example.lirisheng.springbootfinalexperiment.service;

import com.example.lirisheng.springbootfinalexperiment.entity.*;
import com.example.lirisheng.springbootfinalexperiment.entity1.PerInfoEntity;
import com.example.lirisheng.springbootfinalexperiment.pojo.UserAndRoles;
import com.example.lirisheng.springbootfinalexperiment.repositories.*;
import com.example.lirisheng.springbootfinalexperiment.util.GeneralUtil;
import com.example.lirisheng.springbootfinalexperiment.pojo.RegistryEntity;
import com.example.lirisheng.springbootfinalexperiment.util.RespBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ResService {

    @Autowired
    PersonInformationRepository personInformationRepository;

    @Autowired
    UsersRepository usersRepository;

    @Autowired
    AuthoritiesRepository authoritiesRepository;

    @Autowired
    RecordTemperatureRepository recordTemperatureRepository;

    @Autowired
    UserRoleRepository userRoleRepository;

    @Autowired
    RoleRepository roleRepository;

    public final Logger logger = LoggerFactory.getLogger(ResService.class);



    /**
     * 注意:如果在注解{@Transational}的方法中,抛出异常,则会报"Transaction rolled back because it has been marked as rollback-only"
     * 那如何去处理事务中产生的异常呢
     * 解决方法:直接在事务方法中使用try-catch来处理异常
     * 注意:但只使用{@Transational},try-catch是catch不住异常的,只有加上rollbachFor=Exception.class才能catch住
     */

    @Transactional(rollbackFor = Exception.class)
    public void registryResident(Users users, PersonInformation personInformation) throws  Exception {

            users = usersRepository.save(users);
            //添加权限
            List<UserRole> userRoles=new ArrayList<>();
            GeneralUtil.setUserRoleForUsers(userRoles,users.getId());

            personInformation.setId(users.getId());
            personInformationRepository.save(personInformation);


    }

    public  Map<String,Object> findByUsername(String usernamme){
        Map<String,Object> map = new HashMap<>();
        Users users= usersRepository.findByUsername(usernamme);
        if (logger.isDebugEnabled()){
            logger.debug("residentEntity:"+users);
        }
        PersonInformation personInformation = personInformationRepository.findByResId(users.getId());
        map.put("users",users);
        map.put("info",personInformation);
        return  map;
    }

    public List<UserAndRoles> getUserAccountInfo(){

        List<UserAndRoles> userAndRoles=new ArrayList<UserAndRoles>();
        Set<String> roles=null;
        UserAndRoles userAndRoles1=null;
        Iterator<Users> iterator =usersRepository.findAll().iterator();
        while (iterator.hasNext()){
            userAndRoles1.setUsers(iterator.next());
            roles = userRoleRepository.findRoleByUserId(userAndRoles1.getUsers().getId());
            userAndRoles1.setRole(roles);
            userAndRoles.add(userAndRoles1);
        }
        return  userAndRoles;
    }

    public List<PersonInformation> findInfoByName(String name){
        List<PersonInformation>  personInformations= personInformationRepository.findByName(name);
        return  personInformations;
    }

    public List<RecordTemperature> findTempByUserId(Long resId){
        List<RecordTemperature>  recordTemperatures = recordTemperatureRepository.findByResId(resId);
        return recordTemperatures;
    }

    public List<RecordTemperature> findAllTemp(){
        List<RecordTemperature> recordTemperatures = new LinkedList<>();
//        Iterable<PerInfoEntity> perInfoEntities = personInformationRepository.findAll();
        Iterator<RecordTemperature>  recordTemperatureIterator = recordTemperatureRepository.findAll().iterator();
        recordTemperatureIterator.forEachRemaining(recordTemperatures::add);
        return recordTemperatures;
    }

    public PersonInformation getInfoByUserId(Long userId){

        PersonInformation personInformation = personInformationRepository.findByResId(userId);
        return  personInformation;
    }

    public PersonInformation findInfo(String openId){

        //验证是否存在该openId
        Users users = usersRepository.findByOpenId(openId);
//        if(users==null){
//            return RespBean.error("请注册",openId);
//        }
//        if(users.getEnabled()==0){
//            return RespBean.error("账号被锁",openId);
//        }

//        Iterator<String>  roles= userRoleRepository.findRoleByUserId(users.getId()).iterator();
//        boolean flag=false;
//        while (roles.hasNext()){
//            if (roles.next().equals("USER")){
//                flag=true;
//                break;
//            }
//        }
//        if(flag==false){
//            return RespBean.error("权限不对",openId);
//        }

         PersonInformation personInformation = personInformationRepository.findByResId(users.getId());

        return personInformation;


    }

    @Transactional(rollbackFor = Exception.class)
    public void changeInfo(PersonInformation personInformation) throws  Exception{


             personInformationRepository.updateInfoByResId(personInformation.getName(),personInformation.getIdentity(),
                     personInformation.getHouseId(),personInformation.getId());

    }


    public  RespBean judgeRegistryInfo(RegistryEntity registryEntity){

        if((usersRepository.findByUsername(registryEntity.getUsername()))!=null){
            return RespBean.error("账号名已经存在");
        }

        if((usersRepository.findByOpenId(registryEntity.getOpen_id()))!=null){

            return RespBean.error("该微信号已经被绑定");
        }

        if((personInformationRepository.findByHouseId(registryEntity.getHouseId()))!=null){

            return RespBean.error("房号已经存在");
        }

        if((personInformationRepository.findByIdentity(registryEntity.getIdentity()))!=null){

            return RespBean.error("该身份证已经存在");
        }

        return RespBean.ok("成功");
    }

//    public  Map<String,Object> judgeChangeInfo(RegistryEntity registryEntity){
//        Map<String ,Object> map = new LinkedHashMap<>();
//        if(registryEntity.getName()==null || registryEntity.getIdentity()==null||registryEntity.getHouseId()==null){
//            map.put("status",0);
//            map.put("message","填写的信息不能为空");
//            return map;
//        }
//
//        map.put("status",1);
//        return map;
//    }

}
